from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from .models import File, Folder
from .forms import FileUploadForm, FolderCreateForm


# Create your views here.

@login_required
def file_manager(request, folder_id=None):
    user = request.user
    if folder_id:
        folder = get_object_or_404(Folder, id=folder_id, user=user)
        files = File.objects.filter(folder=folder, uploaded_by=user)
        sub_folders = Folder.objects.filter(parent_folder=folder, user=user)
    else:
        folder = None
        files = File.objects.filter(folder__isnull=True, uploaded_by=user)
        sub_folders = Folder.objects.filter(parent_folder__isnull=True, user=user)

    return render(request, 'cloud_disk_app/file_manager.html', {
        'folder_id': folder,
        'files': files,
        'sub_folders': sub_folders,
    })


@login_required
def upload_file(request, folder_id=None):
    user = request.user
    if request.method == 'POST':
        form = FileUploadForm(request.POST, request.FILES)
        if form.is_valid():
            file_instance = form.save(commit=False)
            file_instance.uploaded_by = user
            if folder_id:
                folder = get_object_or_404(Folder, id=folder_id, user=user)
                file_instance.folder = folder
            file_instance.save()
            return redirect('cloud_disk_app:file_manager', folder_id=folder_id)
    else:
        form = FileUploadForm()
    return render(request, 'cloud_disk_app/upload_file.html', {'form': form})


@login_required
def create_folder(request, parent_folder_id=None):
    user = request.user
    if request.method == 'POST':
        form = FolderCreateForm(request.POST)
        if form.is_valid():
            folder_instance = form.save(commit=False)
            folder_instance.user = user
            if parent_folder_id:
                parent_folder = get_object_or_404(Folder, id=parent_folder_id, user=user)
                folder_instance.parent_folder = parent_folder
            folder_instance.save()
            return redirect('cloud_disk_app:file_manager', folder_id=parent_folder_id)
    else:
        form = FolderCreateForm()
    return render(request, 'cloud_disk_app/create_folder.html', {'form': form})
